<template >
  <div>
    <a-form :model="formState" ref="formRef" layout="vertical">
      <a-row :gutter="40">
        <a-col :span="5">
          <a-form-item :label="$t('other.versionName')" :rules="routeRule.name" name="name">
            <a-input
              v-model:value.trim="formState.name"
              :disabled="disabled"
              :placeholder="$t('common.pleaseInput')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="5">
          <a-form-item :label="$t('basicData.section')" name="section" :rules="routeRule.section">
            <a-select
              :placeholder="$t('common.pleaseSelect')"
              allowClear
              v-model:value="formState.section"
              :disabled="disabled"
            >
              <a-select-option
                v-for="(item, index) in [$t('components.dg')]"
                :key="index"
                :value="item"
                >{{ item }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="5">
          <a-form-item :label="t('hangManage.startProcess')" name="firstProcess">
            <a-select
              :placeholder="$t('common.pleaseSelect')"
              allowClear
              v-model:value="formState.firstProcess"
              :disabled="disabled"
            >
              <a-select-option
                v-for="(item, index) in processOption"
                :key="index"
                :value="item.processDetailId"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="5">
          <a-form-item :colon="t('hangManage.endProcess')" name="lastProcess">
            <a-select
              :placeholder="$t('common.pleaseSelect')"
              allowClear
              v-model:value="formState.lastProcess"
              :disabled="disabled"
            >
              <a-select-option
                v-for="(item, index) in processOption"
                :key="index"
                :value="item.processDetailId"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div :class="!evnConfig ? 'roadmap-container' : 'roadmap-container-staff'">
      <a-row>
        <a-col :span="16" class="list-container">
          <a-row class="operate-row">
            <a-col :span="10">{{$t('hangManage.roadList')}}</a-col>
            <a-col :span="14" class="text-right">
              <a-space>
                <a-button type="primary" @click="toggleAll(true)"
                  >{{ $t('common.expandAll') }}</a-button
                >
                <a-button type="primary" @click="toggleAll(false)"
                  >{{ $t('common.packUpAll') }}</a-button
                >
                <a-button type="warning" @click="clearList" v-if="!disabled"
                  >{{ $t('common.clearList') }}</a-button
                >
              </a-space>
            </a-col>
          </a-row>
          <header v-if="!evnConfig">
            <div
              v-for="(item, index) in disabled ? viewRouteHeader : routeHeader"
              :key="index"
            >
              {{ item }}
            </div>
          </header>
          <header v-else>
            <div
              v-for="(item, index) in disabled
                ? viewRouteHeaderWeb
                : routeHeaderWeb"
              :key="index"
            >
              {{ item }}
            </div>
          </header>
          <a-spin :spinning="loading">
            <draggable
              :list="tableList"
              is="draggable"
              :disabled="disabled"
              filter=".forbid"
              handle=".process-box"
              animation="300"
              :scroll="true"
              force-fallback="true"
              group="out"
              item-key="index"
              :allbackOnBody="true"
              @add="add"
              @sort="handleSort"
              @start="handleStart"
              style="min-height: calc(100vh - 510px)"
            >
              <template #item="{ element, index }">
                <div :class="{ forbid: index == 0 }">
                  <div class="relative">
                    <span class="toggle-box">
                      <minus-square-outlined
                        v-if="element.open"
                        @click="
                          () => {
                            element.open = false;
                          }
                        "
                      />
                      <plus-square-outlined
                        v-else
                        @click="
                          () => {
                            element.open = true;
                          }
                        "
                      />
                    </span>
                    <div class="mt-12 process-box">
                      <div>
                        <span>{{ element.sort }}</span>
                      </div>
                      <div>
                        <a-checkbox
                          class="forbid"
                          v-model:checked="element.effect"
                          :disabled="disabled || index == 0"
                          @change="(e) => changeProcessInfo(!e.target.checked)"
                          >{{ $t('hangManage.effect') }}</a-checkbox
                        >
                      </div>
                      <div>
                        <a-checkbox
                          class="forbid"
                          v-model:checked="element.forwardMerge"
                          @change="onCheckChange(element)"
                          :disabled="disabled || index == 0"
                          >{{ $t('other.forwardMerge') }}</a-checkbox
                        >
                      </div>
                      <div>{{ element.processNo }}，{{ element.name }}</div>
                      <div v-if="evnConfig"></div>
                      <div v-if="!disabled" class="forbid">
                        <span
                          class="close-icon"
                          v-if="index != 0"
                          @click="handelCancel(index, false)"
                        >
                          <close-outlined />
                        </span>
                      </div>
                    </div>
                  </div>
                  <draggable
                    v-model="element.moProcRoadmapProcStationList"
                    filter=".nodrag"
                    is="draggable"
                    animation="300"
                    force-fallback="true"
                    group="inner"
                    item-key="index"
                    :allbackOnBody="true"
                    @add="addInner"
                    :disabled="disabled"
                    @start="handleInnerStart"
                  >
                    <template v-slot:item="item">
                      <div class="site-box" v-if="element.open">
                        <div class="relative">
                          <span class="line-icon">
                            <environment-two-tone two-tone-color="#3E8FF7" />
                          </span>
                          <span class="pl-15">
                            {{ item.element.lineNo }}-{{
                              item.element.stationNo
                            }}
                          </span>
                        </div>
                        <div>
                          <!-- <a-checkbox v-model:checked="item.element.receiveHangerBoolean" :disabled="disabled">接收衣架</a-checkbox> -->
                          <a-checkbox
                            v-model:checked="item.element.mainStationBoolean"
                            :disabled="disabled"
                            class="nodrag"
                            >{{ $t('other.assistSit') }}</a-checkbox
                          >
                        </div>
                        <div>
                          {{ item.element.proportion }}
                        </div>
                        <div>
                          {{
                            item.element.type == 1
                              ? $t('other.save')
                              : item.element.type == 2
                              ? $t('other.save')
                              : $t('other.normal')
                          }}
                          <span v-if="showMsg(item.element, 'all')">
                            ，（
                          </span>
                          <span v-if="showMsg(item.element, 'color')"
                            >{{$t('basicData.color') }}：{{
                              item.element.colorList.join(",")
                            }}；</span
                          >
                          <span v-if="showMsg(item.element, 'size')"
                            >{{ $t('basicData.size') }}：
                            {{ item.element.sizeList.join(",") }}；</span
                          >
                          <span v-if="showMsg(item.element, 'po')"
                            >PO： {{ item.element.poList.join(",") }}；</span
                          >
                          <span v-if="showMsg(item.element, 'cutterNo')"
                            >{{$t('hangManage.bedNo')}}：
                            {{ item.element.cutterNoList.join(",") }}；</span
                          >
                          <span v-if="showMsg(item.element, 'tailorBill')"
                            >{{$t('hangManage.cut')}}：
                            {{ item.element.tailorBillList.join(",") }}</span
                          >
                          <span v-if="showMsg(item.element, 'all')"> ）</span>
                        </div>
                        <div v-if="evnConfig">
                          <span v-if="item.element.staffId">
                            {{
                              getFieldText(
                                staffList,
                                item.element.staffId,
                                "id",
                                "staffNo"
                              )
                            }}-{{
                              getFieldText(
                                staffList,
                                item.element.staffId,
                                "id",
                                "nickName"
                              )
                            }}
                            {{
                              getFieldText(
                                staffList,
                                item.element.staffId,
                                "id",
                                "skillGrade"
                              )
                            }}
                            {{
                              arrToStr(
                                staffList,
                                item.element.staffId,
                                "id",
                                "professionNameList"
                              )
                            }}
                          </span>
                        </div>
                        <div v-if="!disabled" class="nodrag">
                          <a-button
                            type="link"
                            class="primary-link"
                            @click="editSite(index, item.index, item.element)"
                            >{{ $t('common.editor') }}</a-button
                          >
                          <span
                            class="close-icon"
                            @click="handelCancel(item.index, true, index)"
                          >
                            <close-outlined />
                          </span>
                        </div>
                      </div>
                    </template>
                  </draggable>
                </div>
              </template>
            </draggable>
          </a-spin>
        </a-col>
        <a-col :span="8" class="choose-container">
          <chooseList
            ref="chooseListRef"
            :processId="processId"
            :tableList="tableList"
            @onOutGroupEnd="onOutGroupEnd"
            @onChooseProcess="onChooseProcess"
            @onInnerGroupEnd="onInnerGroupEnd"
          />
        </a-col>
      </a-row>
      <editStation ref="editStationRef" @ok="onStationOK" />
    </div>
  </div>
</template>

<script setup>
import draggable from "vuedraggable";
import { ref, watch, onMounted, nextTick } from "vue";
import { routeRule } from "./routeChartConfig";
import {
  routeHeader,
  viewRouteHeader,
  routeHeaderWeb,
  viewRouteHeaderWeb,
} from "./routeChartConfig";
import {
  PlusSquareOutlined,
  MinusSquareOutlined,
  CloseOutlined,
  EnvironmentTwoTone,
} from "@ant-design/icons-vue";
import chooseList from "./chooseList.vue";
import editStation from "./editStation.vue";
import { cloneDeep, pick, uniqBy } from "lodash";
import { message } from "ant-design-vue";
import axios from "@/utils/request";
import { useRoute } from "vue-router";
import { getFieldText } from "@/utils";
import i18n from '@/locales/index' 
const { t } = i18n.global

const arrToStr = (ary, value, itemName, field) => {
  const info = ary.filter((i) => i[itemName] == value);
  let arr = info.length ? info[0][field] : [];
  return arr ? `(${arr.join(",")})` : "";
};

let props = defineProps({
  roueteVersionId: {
    require: true,
    default: () => null,
  },
  moInfo: {
    require: true,
    default: () => {},
  },
  staffList: {
    require: true,
    default: () => [],
  },
});
let evnConfig = process.env.VUE_APP_CONFIG;
let disabled = ref(false);
const formState = ref({});
let formRef = ref();
let processOption = ref([]);
let loading = ref(false);
let editStationRef = ref();
let route = useRoute();
let tableList = ref([]);
let routeInfo = ref({});
let chooseListRef = ref({});
let originList = ref(tableList.value);
let sortFlag = ref(false);
let sortInnerFlag = ref(false);
let processId = ref(null); // 工序版本id
let editProcIndex = ref(0);
let editStationIndex = ref(0);
let isAdd = ref(false);
let isEdit = ref(false);
let originSortList = ref([]);
let maxNum = ref(0);

const handleStart = () => {
  sortFlag.value = true;
  originList.value = cloneDeep(tableList.value);
};
const changeProcessInfo = (isDelete) => {
  processOption.value = tableList.value.filter((i) => i.effect);
  if (isDelete) {
    formState.value.firstProcess = undefined;
    formState.value.lastProcess = undefined;
  }
};
const add = async (e) => {
  sortFlag.value = false;
  await nextTick();
  if (e.newIndex === 0) {
    message.warning(t('other.firstStationMCanHang') );
    tableList.value.splice(0, 1);
    initSortInfo();
  }
  changeProcessInfo();
};
const handleSort = (e) => {
  if (sortFlag.value) {
    if (e.newIndex == 0) {
      message.warning(t('other.firstStationMCanHangProcess'));
      tableList.value = originList.value;
    } else {
      initSortInfo();
      tableList.value.forEach((i, index) => {
        i.sort = originSortList.value[index];
      });
    }
  }
};
const handelCancel = (key, isInner, outKey) => {
  if (isInner) {
    tableList.value[outKey].moProcRoadmapProcStationList.splice(key, 1);
  } else {
    tableList.value.splice(key, 1);
    initSortInfo();
    changeProcessInfo(true);
  }
};
const onOutGroupEnd = () => {
  tableList.value = tableList.value.map((i) => {
    let obj = { ...i };
    if (obj.open == undefined) obj.open = true;
    obj.moProcRoadmapProcStationList = obj.moProcRoadmapProcStationList || [];
    if (!obj.sort) {
      let newSortNo = ++maxNum.value;
      obj.sort = newSortNo;
    }
    return obj;
  });
  initSortInfo();

  tableList.value.forEach((i, index) => {
    i.sort = originSortList.value[index];
  });
};
const handleInnerStart = () => {
  sortInnerFlag.value = true;
  originList.value = cloneDeep(tableList.value);
};
const onSortInner = () => {
  let lists = cloneDeep(tableList.value);
  let flag1 = lists[0].moProcRoadmapProcStationList.some((i) => i.role != "2");
  lists.splice(0, 1);
  let flag2 = lists
    .reduce((prev, next) => {
      return prev.concat(
        ...(next.moProcRoadmapProcStationList
          ? next.moProcRoadmapProcStationList
          : [])
      );
    }, [])
    .some((i) => i.role == 2);
  if (flag1) message.warning(t('other.firstProcessCanHang'));
  if (flag2) message.warning(t('other.hangStationMustDownFirstProcessCanHang'));
  let mergeFlag = lists.some(
    (i) => i.forwardMerge && i.moProcRoadmapProcStationList.length > 0
  );
  if (mergeFlag) message.warning(t('other.forwardMergeProcess'));
  let isUniq = lists.every(
    (i) => isUniqInner(i.moProcRoadmapProcStationList).isUniq
  );
  if (flag1 || flag2 || mergeFlag || !isUniq)
    tableList.value = originList.value;
};
const isUniqInner = (list) => {
  let uniqList = uniqBy(list, "stationId");
  let isUniq = uniqList.length == list.length;
  if (!isUniq) message.warning(t('other.sameProcessCanNotSameStation'));
  return {
    isUniq,
    uniqList,
  };
};
const onAddInner = () => {
  tableList.value.forEach((el, index) => {
    if (index == 0) {
      if (
        el.moProcRoadmapProcStationList &&
        el.moProcRoadmapProcStationList.some((i) => i.role != "2")
      ) {
        message.warning(t('other.firstProcessCanHang'));
        el.moProcRoadmapProcStationList =
          el.moProcRoadmapProcStationList.filter((i) => i.role == "2");
      }
      let isUniqInfo = isUniqInner(el.moProcRoadmapProcStationList);
      if (!isUniqInfo.isUniq)
        el.moProcRoadmapProcStationList = isUniqInfo.uniqList;
    } else {
      if (el.forwardMerge) {
        if (el.moProcRoadmapProcStationList.length > 0) {
          message.warning(t('other.forwardMergeProcess'));
          el.moProcRoadmapProcStationList = [];
        }
      } else {
        if (
          el.moProcRoadmapProcStationList &&
          el.moProcRoadmapProcStationList.some((i) => i.role == "2")
        ) {
          message.warning(t('other.hangStationMustDownFirstProcessCanHang'));
          el.moProcRoadmapProcStationList =
            el.moProcRoadmapProcStationList.filter((i) => i.role != "2");
        }

        let isUniqInfo = isUniqInner(el.moProcRoadmapProcStationList);
        if (!isUniqInfo.isUniq)
          el.moProcRoadmapProcStationList = isUniqInfo.uniqList;
      }
    }
  });
};
const addInner = async () => {
  await nextTick();
  if (sortInnerFlag.value) {
    onSortInner();
  } else {
    onAddInner();
  }
  sortInnerFlag.value = false;
};
const onInnerGroupEnd = () => {
  tableList.value.map((el) => {
    el.moProcRoadmapProcStationList = el.moProcRoadmapProcStationList.map(
      (i) => ({ ...i })
    );
    return el;
  });
};
const toggleAll = (open) => {
  tableList.value.forEach((i) => {
    i.open = open;
  });
};
const clearList = () => {
  let lists = cloneDeep(tableList.value).splice(0, 1);
  lists[0].moProcRoadmapProcStationList = [];
  tableList.value = lists;
  initSortInfo();
  changeProcessInfo(true);
};
const onCheckChange = (element) => {
  if (element.forwardMerge) element.moProcRoadmapProcStationList = [];
};
const editSite = (parentIndex, index, record) => {
  let name = `${record.lineNo}-${record.stationNo}`;
  editProcIndex.value = parentIndex;
  editStationIndex.value = index;
  editStationRef.value.edit(name, record, props.moInfo, props.staffList);
};
const onStationOK = (value) => {
  let datas = cloneDeep(tableList.value);
  datas.forEach((item, index) => {
    if (index == editProcIndex.value) {
      item.moProcRoadmapProcStationList &&
        item.moProcRoadmapProcStationList.map((el, i) => {
          if (i == editStationIndex.value) {
            Object.assign(el, value);
          }
          return el;
        });
    }
  });
  tableList.value = datas;
};
const initFormInfo = async (info) => {
  let formValue =
    !isAdd.value &&
    pick(info, ["name", "firstProcess", "lastProcess", "section"]);
  if (!formValue.section) formValue.section = t('components.dg');
  await nextTick();
  formState.value = formValue;
};
const initAddFormInfo = async () => {
  formState.value.section = t('components.dg')
  // try {
  //   let res = await axios.getAction('/api/mo/mo-proc-roadmap/roadmap-name', { id: route.query.id })
  //   if (res.success) formState.value.name = res.data
  // } catch {
  //   console.error('路线图版本名称获取失败')
  // }
};
const initSortInfo = () => {
  originSortList.value = tableList.value
    .map((i) => i.sort)
    .filter((i) => i != undefined)
    .sort((a, b) => a - b);
  maxNum.value = Math.max(...originSortList.value);
};
const initTableList = (list, isNew) => {
  list.forEach((i) => {
    i.open = true;
    i.forwardMerge = i.forwardIntegration == 1;
    i.enable = isNew ? 1 : i.enable;
    i.effect = i.enable == 1;
    if (i.moProcRoadmapProcStationList) {
      i.moProcRoadmapProcStationList.forEach((i) => {
        i.mainStationBoolean = i.mainAuxiliaryStation == 2;
      });
    } else {
      i.moProcRoadmapProcStationList = [];
    }
  });
  tableList.value = list;
  initSortInfo();
};
const initRouteListInfo = (info) => {
  routeInfo.value = info;
  processId.value = isAdd.value ? null : info.processId;
  initTableList(info.moProcRoadmapProcList || []);
  changeProcessInfo();
};
// 路线图详细信息
const getVersionRouteInfo = async (versionId) => {
  loading.value = true;
  try {
    const res = await axios.getAction("/api/mo/mo-proc-roadmap/get", {
      id: versionId,
    });
    initFormInfo(res.data || {});
    initRouteListInfo(res.data || {});
  } catch {
    routeInfo.value = {};
  }
  loading.value = false;
};
const showMsg = (record, type) => {
  if (type == "all") {
    return [
      "colorList",
      "sizeList",
      "poList",
      "cutterNoList",
      "tailorBillList",
    ].some((i) => record[i] && record[i].length);
  } else {
    return record[`${type}List`] && record[`${type}List`].length;
  }
};
const onChooseProcess = (list, processVersionId) => {
  list.forEach((i, index) => {
    i.sort = index + 1;
  });
  initTableList(list, true);
  processOption.value = tableList.value.filter((i) => i.effect);
  processId.value = processVersionId;
};

defineExpose({
  formRef,
  formState,
  processId,
  tableList,
});
watch(
  () => props.roueteVersionId,
  (newVal) => {
    if (newVal && !isAdd.value) getVersionRouteInfo(newVal);
  },
  { deep: true, immediate: true }
);

onMounted(async () => {
  tableList.value = [];
  originSortList.value = [];
  disabled.value = route.path == "/makeManage/routeChart/details";
  isAdd.value = route.path == "/makeManage/routeChart/add";
  isEdit.value = route.path == "/makeManage/routeChart/edit";
  if (isAdd.value) initAddFormInfo();
});
</script>